const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let data = this.post()
    let userInfo = await this.session('user_info')
    if (!userInfo) return this.fail(-1, '未登录授权')
    let alipaySdk = await think.alipaySdk()
    if (data.money <= 0) return this.fail(-1, '提现金额错误')
    

    let dealList = await this.model('deal/index').all(userInfo._id)
    let money = 0
    let addType = ['commission', 'deduct', 'charge']
    let reduceType = ['upgrade', 'cash']
    dealList.forEach(item => {
      if (addType.indexOf(item.type) != -1) {
        money += item.money
      } else if (reduceType.indexOf(item.type) != -1) {
        money -= item.money
      }
    })

    if ( parseFloat(data.money) > money) return this.fail(-1, '提现金额错误')

    /// 生成交易订单
    let deal = await this.model('deal/index').add({
      type: 'cash',
      uid: userInfo._id,
      money: data.money,
      status: 1,
      remark: '发起提现操作'
    })

    let id = deal._id.toString()
    let result
    try {
      result = await this.model('alipay/index').cash(alipaySdk, {
        out_biz_no: id, 
        trans_amount: data.money,
        product_code: 'TRANS_ACCOUNT_NO_PWD',
        biz_scene: 'DIRECT_TRANSFER',
        order_title: '提现到账',
        payee_info: {
          identity: data.alipay,
          identity_type: 'ALIPAY_LOGON_ID',
          name: data.name
        }
      })
    } catch (e) {}
    if (result && result.code == '10000' && result.msg == 'Success' && result.status == 'SUCCESS') {
      this.json({
        status: 200, message: 'success'
      })
    } else {
      await this.model('deal/index').setPay(id, 2, JSON.stringify(result))
      this.fail(-1, result.msg || '提现异常')
    }
  }
};
